package net.youpo.Market.UI.Manager;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import net.youpo.Market.R;
import net.youpo.Market.Download.Downloads;
import net.youpo.Market.Net.HttpConnection;
import net.youpo.Market.Util.ConstantsTable;
import net.youpo.Market.Util.Tools;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class DownloadManagerAdapter extends BaseExpandableListAdapter {
	public static final int GROUP_ID_DOWNLOAD_UNFINISHED = 0;
	public static final int GROUP_ID_DOWNLOAD_FINISHED = 1;
	private LayoutInflater inflater;
	Cursor child1Cursor, child2Cursor;
	private Vector<DataSetObserver> mObservers;
	List<String> group; // 组列表
	List<ArrayList<AudioValueDownloadItem>> child; // 子列表
	private Map<Integer, Cursor> childCursorMap;
	private Context mContext;
	private ChangeObserver mChange1Observer, mChange2Observer;
	private final int PAUSE = 1;
	private final int RESUME = 2;
	private final int INSTALL = 3;
	private final String REQS_CONFIG = "Push/Install";
	private byte[] lock = new byte[0];

	public DownloadManagerAdapter(Context context,
			Map<Integer, Cursor> cursorMap) {
		inflater = LayoutInflater.from(context);
		mContext = context;
		mObservers = new Vector<DataSetObserver>();
		childCursorMap = new HashMap<Integer, Cursor>();
		setchildCursors(cursorMap);
		mChange1Observer = new ChangeObserver();
		mChange2Observer = new ChangeObserver();
		child1Cursor = childCursorMap.get(GROUP_ID_DOWNLOAD_UNFINISHED);
		child2Cursor = childCursorMap.get(GROUP_ID_DOWNLOAD_FINISHED);
		// registerContentObserver();
		group = new ArrayList<String>();
		child = new ArrayList<ArrayList<AudioValueDownloadItem>>();
		initializeData(context);
	}

	public void setchildCursors(Map<Integer, Cursor> cursorMap) {
		childCursorMap = cursorMap;
	}

	private class ChangeObserver extends ContentObserver {
		public ChangeObserver() {
			super(new Handler());
		}

		@Override
		public boolean deliverSelfNotifications() {
			return true;
		}

		@Override
		public void onChange(boolean selfChange) {
			Log.e("onChange", "DownloadManagerAdapter onChange");
			refreshData();
		}
	}

	void refreshData() {
		if (child1Cursor.isClosed()) {
			return;
		}
		child1Cursor.requery();
		if (child2Cursor.isClosed()) {
			return;
		}
		child2Cursor.requery();
		for (DataSetObserver o : mObservers) {
			o.onChanged();
		}
		synchronized (lock) {
			initializeData(mContext);
		}
	}

	/**
	 * 初始化组、子列表数据
	 */
	public void initializeData(Context context) {
		group.clear();
		child.clear();
		String groupName = "";
		groupName = "正在下载";
		ArrayList<AudioValueDownloadItem> childitem = new ArrayList<AudioValueDownloadItem>();
		if (child1Cursor != null && child1Cursor.getCount() != 0) {
			for (child1Cursor.moveToFirst(); !child1Cursor.isAfterLast(); child1Cursor
					.moveToNext()) {
				AudioValueDownloadItem audioValueDownloadItem = new AudioValueDownloadItem();
				audioValueDownloadItem.id = child1Cursor.getLong(child1Cursor
						.getColumnIndex(Downloads.Impl._ID));
				audioValueDownloadItem.title = child1Cursor
						.getString(child1Cursor
								.getColumnIndex(Downloads.Impl.COLUMN_TITLE));
				audioValueDownloadItem.description = child1Cursor
						.getString(child1Cursor
								.getColumnIndex(Downloads.Impl.COLUMN_DESCRIPTION));
				audioValueDownloadItem.status = child1Cursor
						.getInt(child1Cursor
								.getColumnIndex(Downloads.Impl.COLUMN_STATUS));
				audioValueDownloadItem.totalBytes = child1Cursor
						.getLong(child1Cursor
								.getColumnIndex(Downloads.Impl.COLUMN_TOTAL_BYTES));
				audioValueDownloadItem.currentBytes = child1Cursor
						.getLong(child1Cursor
								.getColumnIndex(Downloads.Impl.COLUMN_CURRENT_BYTES));
				audioValueDownloadItem.iconUrl = child1Cursor
						.getString(child1Cursor
								.getColumnIndex(Downloads.Impl.COLUMN_ICON_URL));
				audioValueDownloadItem.appId = child1Cursor
						.getString(child1Cursor
								.getColumnIndex(Downloads.Impl.COLUMN_APP_ID));
				childitem.add(audioValueDownloadItem);
			}
		}
		addAudioInfo(groupName, childitem);

		groupName = "未安装";
		childitem = new ArrayList<AudioValueDownloadItem>();
		if (child2Cursor != null && child2Cursor.getCount() != 0) {
			for (child2Cursor.moveToFirst(); !child2Cursor.isAfterLast(); child2Cursor
					.moveToNext()) {
				AudioValueDownloadItem audioValueDownloadItem = new AudioValueDownloadItem();
				audioValueDownloadItem.id = child2Cursor.getLong(child2Cursor
						.getColumnIndex(Downloads.Impl._ID));
				audioValueDownloadItem.title = child2Cursor
						.getString(child2Cursor
								.getColumnIndex(Downloads.Impl.COLUMN_TITLE));
				audioValueDownloadItem.description = child2Cursor
						.getString(child2Cursor
								.getColumnIndex(Downloads.Impl.COLUMN_DESCRIPTION));
				audioValueDownloadItem.status = child2Cursor
						.getInt(child2Cursor
								.getColumnIndex(Downloads.Impl.COLUMN_STATUS));
				audioValueDownloadItem.totalBytes = child2Cursor
						.getLong(child2Cursor
								.getColumnIndex(Downloads.Impl.COLUMN_TOTAL_BYTES));
				audioValueDownloadItem.currentBytes = child2Cursor
						.getLong(child2Cursor
								.getColumnIndex(Downloads.Impl.COLUMN_CURRENT_BYTES));
				audioValueDownloadItem.iconUrl = child2Cursor
						.getString(child1Cursor
								.getColumnIndex(Downloads.Impl.COLUMN_ICON_URL));
				audioValueDownloadItem.appId = child2Cursor
						.getString(child1Cursor
								.getColumnIndex(Downloads.Impl.COLUMN_APP_ID));
				childitem.add(audioValueDownloadItem);
			}
		}
		addAudioInfo(groupName, childitem);

	}

	private void addAudioInfo(String g,
			ArrayList<AudioValueDownloadItem> valueItem) {
		group.add(g);
		child.add(valueItem);
	}

	private class AudioDownloadItem {
		private ImageView icon;
		private TextView title;
		private TextView downloadProgress;
		private ImageView controlBtn;
		private LinearLayout btnView;
		private TextView btnText;
	}

	public class AudioValueDownloadItem {
		public long id;
		public String title;
		public String description;
		public int status;
		public long totalBytes;
		public long currentBytes;
		public String iconUrl;
		public String appId;

	}

	@Override
	public View getGroupView(int groupPosition, boolean isExpanded,
			View convertView, ViewGroup parent) {
		String string = group.get(groupPosition);
		View view = inflater.inflate(R.layout.appdownload_group_layout, null);
		TextView downGroupInfoView = (TextView) view
				.findViewById(R.id.download_group_title);
		ImageView downGroupIndicator = (ImageView) view
				.findViewById(R.id.download_group_Indicator);
		downGroupInfoView.setText(string);
		if (isExpanded) {
			downGroupIndicator.setImageResource(R.drawable.download_group_open);
		} else {
			downGroupIndicator
					.setImageResource(R.drawable.download_group_close);
		}
		return view;
	}

	@Override
	public Object getChild(int groupPosition, int childPosition) {
		return child.get(groupPosition).get(childPosition);
	}

	@Override
	public long getChildId(int groupPosition, int childPosition) {
		return 0;
	}

	@Override
	public View getChildView(final int groupPosition, final int childPosition,
			boolean isLastChild, View convertView, ViewGroup parent) {
		synchronized (lock) {
			if (child.get(groupPosition).isEmpty()) {
				return convertView;
			}
			AudioValueDownloadItem childItem = null;
			try {
				childItem = child.get(groupPosition).get(childPosition);
			} catch (Exception e) {
				Log.e("H3c", "error 842");
				return convertView;
			}
			final AudioDownloadItem audioDownloadItem;
			if (null == convertView) {
				convertView = inflater.inflate(R.layout.appdownload_adapter,
						null);
				audioDownloadItem = new AudioDownloadItem();
				audioDownloadItem.icon = (ImageView) convertView
						.findViewById(R.id.download_icon);
				audioDownloadItem.title = (TextView) convertView
						.findViewById(R.id.download_title);
				audioDownloadItem.downloadProgress = (TextView) convertView
						.findViewById(R.id.progress_text);
				audioDownloadItem.btnText = (TextView) convertView
						.findViewById(R.id.btn_text);
				audioDownloadItem.controlBtn = (ImageView) convertView
						.findViewById(R.id.control_btn);
				audioDownloadItem.btnView = (LinearLayout) convertView
						.findViewById(R.id.btn_group);

				audioDownloadItem.btnView
						.setOnClickListener(new View.OnClickListener() {
							@Override
							public void onClick(View v) {
								Long id = (Long) ((View) v.getParent())
										.getTag();
								if (id != null) {
									switch ((Integer) audioDownloadItem.btnView
											.getChildAt(0).getTag()) {
									case PAUSE:
										// Toast.makeText(mContext, "pause",
										// Toast.LENGTH_SHORT).show();
										pauseDownload((Long) id);
										audioDownloadItem.controlBtn
												.setTag(RESUME);
										audioDownloadItem.controlBtn
												.setBackgroundResource(R.drawable.download_resume);
										break;
									case RESUME:
										// Toast.makeText(mContext, "resume",
										// Toast.LENGTH_SHORT).show();
										resumeDownload((Long) id);
										audioDownloadItem.controlBtn
												.setTag(PAUSE);
										audioDownloadItem.controlBtn
												.setBackgroundResource(R.drawable.download_pause);
										break;
									case INSTALL:
										// Toast.makeText(mContext, "install",
										// Toast.LENGTH_SHORT).show();
										Cursor c = mContext
												.getContentResolver()
												.query(ContentUris
														.withAppendedId(
																Downloads.Impl.CONTENT_URI,
																id), null,
														null, null, null);
										c.moveToFirst();
										Intent i = new Intent(
												Intent.ACTION_VIEW);
										String filePath = c.getString(c
												.getColumnIndex(Downloads.Impl._DATA));
										final String recommend_id = c.getString(c
												.getColumnIndex(Downloads.Impl.COLUMN_RECOMMEND_ID));
										Log.e("resultJson", "result:"
												+ recommend_id);
										i.setDataAndType(
												Uri.parse("file://" + filePath),
												"application/vnd.android.package-archive");
										mContext.startActivity(i);
										c.close();
										if (!recommend_id.equals("")) {
											Toast.makeText(mContext,
													"install recommend app",
													Toast.LENGTH_SHORT).show();
											new Thread(new Runnable() {
												@Override
												public void run() {
													StringBuffer sb = new StringBuffer();
													sb.append("vc="
															+ ConstantsTable.NOW_VERSION
															+ "&imei="
															+ ConstantsTable.IMEI
															+ "&id="
															+ recommend_id);
													HttpConnection hc = new HttpConnection();
													String resultJson = hc
															.requestService2(
																	REQS_CONFIG,
																	sb);
													Log.e("resultJson",
															"result:"
																	+ resultJson);
												}
											}).start();
											break;
										}
									}
								}
							}
						});

				// audioDownloadItem.controlBtn.setOnClickListener(new
				// View.OnClickListener() {
				// @Override
				// public void onClick(View v) {
				// Long id = (Long)((View) v.getParent().getParent()).getTag();
				// if (id != null) {
				// switch ((Integer) v.getTag()) {
				// case PAUSE:
				// Toast.makeText(mContext, "pause", Toast.LENGTH_SHORT).show();
				// pauseDownload((Long)id);
				// audioDownloadItem.controlBtn.setTag(RESUME);
				// audioDownloadItem.controlBtn.setBackgroundResource(R.drawable.download_resume);
				// break;
				// case RESUME:
				// Toast.makeText(mContext, "resume",
				// Toast.LENGTH_SHORT).show();
				// resumeDownload((Long)id);
				// audioDownloadItem.controlBtn.setTag(PAUSE);
				// audioDownloadItem.controlBtn.setBackgroundResource(R.drawable.download_pause);
				// break;
				// case INSTALL:
				// Toast.makeText(mContext, "install",
				// Toast.LENGTH_SHORT).show();
				// Cursor c = mContext.getContentResolver().query(
				// ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI,
				// id), null, null, null, null);
				// c.moveToFirst();
				// Intent i = new Intent(Intent.ACTION_VIEW);
				// String filePath =
				// c.getString(c.getColumnIndex(Downloads.Impl._DATA));
				// i.setDataAndType(Uri.parse("file://" +
				// filePath),"application/vnd.android.package-archive");
				// mContext.startActivity(i);
				// c.close();
				// break;
				// }
				// }
				// }
				// });
				convertView.setTag(R.layout.appdownload_adapter,
						audioDownloadItem);
			} else {
				audioDownloadItem = (AudioDownloadItem) convertView
						.getTag(R.layout.appdownload_adapter);
			}
			File file = new File(ConstantsTable.CACHE_PATH + "/"
					+ childItem.appId);
			Bitmap bmp = null;
			if (file.exists()) {// 如果有缓存文件
				bmp = Tools.getBitmapFromCache(ConstantsTable.CACHE_PATH + "/"
						+ childItem.appId);
				Drawable drawable = new BitmapDrawable(bmp);
				audioDownloadItem.icon.setBackgroundDrawable(drawable);
			} else {
				audioDownloadItem.icon.setBackgroundResource(R.drawable.icon);
			}
			// else {// 没有缓存就从网络获取
			// HttpConnection hc = new HttpConnection();
			// bmp = hc.getNetworkBitmap(childItem.iconUrl);
			//
			// Tools.saveBmpToSd(bmp, childItem.appId);// 保存至缓存
			// }
			audioDownloadItem.title.setText(childItem.title);
			int progressAmount = 0;
			if (childItem.totalBytes != 0)
				progressAmount = (int) (childItem.currentBytes * 100 / childItem.totalBytes);
			audioDownloadItem.downloadProgress.setVisibility(View.VISIBLE);
			if (Downloads.isStatusCompleted(childItem.status)) { // Download
																	// stopped
				if (Downloads.isStatusError(childItem.status)) {
					audioDownloadItem.controlBtn.setTag(RESUME);
					audioDownloadItem.controlBtn
							.setBackgroundResource(R.drawable.download_resume);
					audioDownloadItem.btnText.setText("继续");
					audioDownloadItem.downloadProgress.setTextColor(Color
							.parseColor("#AA947F"));
					audioDownloadItem.downloadProgress.setText("已暂停"
							+ progressAmount + "%");
				} else {
					audioDownloadItem.controlBtn.setTag(INSTALL);
					audioDownloadItem.controlBtn
							.setBackgroundResource(R.drawable.download_install);
					audioDownloadItem.btnText.setText("安装");
					audioDownloadItem.downloadProgress.setVisibility(View.GONE);
				}
			} else { // Download is still running
				if (childItem.status == Downloads.STATUS_PENDING) {
					audioDownloadItem.controlBtn.setTag(PAUSE);
					audioDownloadItem.controlBtn
							.setBackgroundResource(R.drawable.download_pause);
					audioDownloadItem.btnText.setText("暂停");
					audioDownloadItem.downloadProgress.setTextColor(Color
							.parseColor("#1E9320"));
					audioDownloadItem.downloadProgress.setText("正在下载"
							+ progressAmount + "%");
				} else if (childItem.status == Downloads.STATUS_PENDING_PAUSED) {
					audioDownloadItem.controlBtn.setTag(PAUSE);
					audioDownloadItem.controlBtn
							.setBackgroundResource(R.drawable.download_pause);
					audioDownloadItem.btnText.setText("暂停");
					audioDownloadItem.downloadProgress.setTextColor(Color
							.parseColor("#1E9320"));
					audioDownloadItem.downloadProgress.setText("正在下载"
							+ progressAmount + "%");
				} else {
					if (childItem.status == Downloads.STATUS_RUNNING) {
						audioDownloadItem.controlBtn.setTag(PAUSE);
						audioDownloadItem.controlBtn
								.setBackgroundResource(R.drawable.download_pause);
						audioDownloadItem.btnText.setText("暂停");
						audioDownloadItem.downloadProgress.setTextColor(Color
								.parseColor("#1E9320"));
						audioDownloadItem.downloadProgress.setText("正在下载"
								+ progressAmount + "%");
					} else {
						audioDownloadItem.controlBtn.setTag(RESUME);
						audioDownloadItem.controlBtn
								.setBackgroundResource(R.drawable.download_resume);
						audioDownloadItem.btnText.setText("继续");
						audioDownloadItem.downloadProgress.setTextColor(Color
								.parseColor("#AA947F"));
						audioDownloadItem.downloadProgress.setText("已暂停"
								+ progressAmount + "%");
					}
				}
			}
			convertView.setTag(childItem.id);
			return convertView;
		}
	}

	public void pauseDownload(long id) {
		pauseDownload(ContentUris
				.withAppendedId(Downloads.Impl.CONTENT_URI, id));
	}

	public void pauseDownload(Uri uri) {

		ContentValues values = new ContentValues();
		values.put(Downloads.Impl.COLUMN_CONTROL, Downloads.Impl.CONTROL_PAUSED);
		mContext.getContentResolver().update(uri, values, null, null);
	}

	public void resumeDownload(long id) {
		resumeDownload(ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI,
				id));
	}

	public void resumeDownload(Uri uri) {

		ContentValues values = new ContentValues();
		values.put(Downloads.Impl.COLUMN_CONTROL, Downloads.Impl.CONTROL_RUN);
		mContext.getContentResolver().update(uri, values, null, null);
	}

	@Override
	public int getChildrenCount(int groupPosition) {
		return child.get(groupPosition).size();
	}

	@Override
	public Object getGroup(int groupPosition) {
		return group.get(groupPosition);
	}

	@Override
	public int getGroupCount() {
		return group.size();
	}

	@Override
	public long getGroupId(int groupPosition) {
		return 0;
	}

	@Override
	public boolean hasStableIds() {
		return false;
	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		return true;
	}

	public void registerContentObserver() {
		if (mChange1Observer != null) {
			child1Cursor.registerContentObserver(mChange1Observer);
		}
		if (mChange2Observer != null) {
			child2Cursor.registerContentObserver(mChange2Observer);
		}
	}

	public void unregisterContentObserver() {
		if (mChange1Observer != null) {
			child1Cursor.unregisterContentObserver(mChange1Observer);
		}
		if (mChange2Observer != null) {
			child2Cursor.unregisterContentObserver(mChange2Observer);
		}
	}

	public void registerDataSetObserver(DataSetObserver observer) {
		mObservers.add(observer);
	}

	public void unregisterDataSetObserver(DataSetObserver observer) {
		mObservers.remove(observer);
	}
}
